<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @open="handleOpen" @close="handleClose">
    <!-- 角色列表 -->
    <el-checkbox-group v-model="selectedList" v-loading="loading" class="assign-role">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="handleSubmit">确定</el-button>
      <el-button size="small" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { reqGetRoleList } from '../../../api/settings'
import { getDetailInfo } from '../../../api/user'
import { reqAssignRoles } from '../../../api/employees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      required: true
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      loading: false,
      selectedList: [],
      roleList: []
    }
  },
  methods: {
    handleClose () {
      this.$emit('update:showRoleDialog', false)
    },
    // 处理弹窗打开
    async handleOpen () {
      // const ret = await reqGetRoleList({ page: 1, pagesize: 10000 })
      // if (ret.code === 10000) {
      //   this.roleList = ret.data.rows
      // }
      // const ret1 = await getDetailInfo(this.userId)
      // if (ret1.code === 10000) {
      //   this.selectedList = ret1.data.roleIds
      // }

      // 获取该用户默认拥有的角色
      const info = getDetailInfo(this.userId)
      // 获取所有的角色列表数据
      const ret = reqGetRoleList({ page: 1, pagesize: 10000 })
      // 并发触发多个异步任务
      Promise.all([info, ret]).then(result => {
        // 如果没有值的话那么是NULL,但是selectedList至少应该是个空数组
        this.selectedList = result[0].data.roleIds || []
        this.roleList = result[1].data.rows
      }).catch(() => {
        this.$message.error('获取角色列表失败')
      }).finally(() => {
        this.loading = false
      })
    },
    async handleSubmit () {
      try {
        const ret = await reqAssignRoles(
          // 下面是看文档需要传的参数
          {
            // 用户id
            id: this.userId,
            // 选中的角色列表
            roleIds: this.roleList
          }
        )
        if (ret.code === 10000) {
          // 分配角色成功
          this.handleClose()
        }
      } catch {
        this.$message.error('分配角色失败')
      }
    }
  }
}
</script>
